import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable, tap } from 'rxjs';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const req = context.switchToHttp().getRequest(); // 获取 HTTP 请求对象
    const { method, url } = req; // 从请求对象中获取 HTTP 方法和 URL
    const now = Date.now(); // 获取当前时间戳
    return next.handle().pipe( // 调用下一个拦截器或处理程序
      tap(() => {
        const ms = Date.now() - now; // 计算请求处理时间
        console.log(`[${method}] ${url} - ${ms}ms`); // 打印日志
      }),
    );
  }
}